
const app = getApp()
const imagePathH = '../../images/'
const device = wx.getSystemInfoSync();


Page({
  data: {
    tempCanvasWidth: 0,
    tempCanvasHeight: 0,
    imgViewHeight: 0,
    imgViewWidth: 0,
    imgViewBgHeight: 0,
    minScale: 0.5,
    maxScale: 2.5,
    doodleImageSrc: '',
    tempImageSrc: '',
    originImageSrc: '',
    imgWidth: 0,
    imgHeight: 0,
    imgTop: 0,
    imgLeft: 0,
    imageLeftAndRightGap: 60,
    isCroper: false,
    events: undefined,
    // 底部展示高度:
    showBottomViewHeight: 106 + app.globalData.bottomSafeHeight,
    showSocllViewW: app.globalData.windowWidth - 30,
    // 基准宽度
    criterionW: 750,
    // 保存后返回
    isSaveBack: false,
    // 选中模板id
    selectModelIndex: 0,
    // 裁剪框 宽高
    cutW: 0,
    cutH: 0,
    cutL: 0,
    cutT: 0,
    // 裁剪框需要的图片
    cutTopLeftAngleImg: imagePathH + 'icon_cut_angle_Top_left.png',
    cutTopRightAngleImg: imagePathH + 'icon_cut_angle_Top_right.png',
    cutBottomLeftAngleImg: imagePathH + 'icon_cut_angle_bottom_left.png',
    cutBottomRightAngleImg: imagePathH + 'icon_cut_angle_bottom_right.png',
    // 可选比例数组
    modelList: [
      {
        // 自由
        defaultIcon: imagePathH + 'icon_cut_sacle_auto.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_auto_select.png',
        sacleW: 0,
        sacleH: 0,
      },
      {
        // 手机比例
        defaultIcon: imagePathH + 'icon_cut_sacle_divce.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_divce_select.png',
        sacleW: wx.getSystemInfoSync().windowWidth,
        sacleH: wx.getSystemInfoSync().windowHeight,
      },
      {
        // 1:1
        defaultIcon: imagePathH + 'icon_cut_sacle_1_1.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_1_1_select.png',
        sacleW: 1,
        sacleH: 1,
      },
      {
        // 2:3
        defaultIcon: imagePathH + 'icon_cut_sacle_2_3.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_2_3_select.png',
        sacleW: 2,
        sacleH: 3,
      },
      {
        // 3:2
        defaultIcon: imagePathH + 'icon_cut_sacle_3_2.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_3_2_select.png',
        sacleW: 3,
        sacleH: 2,
      },

      {
        // 3:4
        defaultIcon: imagePathH + 'icon_cut_sacle_3_4.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_3_4_select.png',
        sacleW: 3,
        sacleH: 4,
      },

      {
        // 4:3
        defaultIcon: imagePathH + 'icon_cut_sacle_4_3.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_4_3_select.png',
        sacleW: 4,
        sacleH: 3,
      },
      {
        // 9:16
        defaultIcon: imagePathH + 'icon_cut_sacle_9_16.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_9_16_select.png',
        sacleW: 9,
        sacleH: 16,
      },
      {
        // 16:9
        defaultIcon: imagePathH + 'icon_cut_sacle_16_9.png',
        selelctIcon: imagePathH + 'icon_cut_sacle_16_9_select.png',
        sacleW: 16,
        sacleH: 9,
      },

    ]

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    console.log('option', option);
    var self = this

    // 获取当前的父类方法
    const eventChannel = this.getOpenerEventChannel()
    if (eventChannel) {
      this.setData({
        events: eventChannel,
      })
    }

    self.device = device;
    self.imageLeftAndRightGap = self.data.imageLeftAndRightGap
    self.imgViewHeight = self.device.windowHeight - self.data.showBottomViewHeight
    self.imgViewWidth = self.device.windowWidth
    self.imgViewBgHeight = self.device.windowHeight - self.data.showBottomViewHeight;

    self.setData({
      imgViewHeight: self.imgViewHeight,
      imgViewWidth: self.imgViewWidth,
      imgViewBgHeight: self.imgViewBgHeight,
      tempCanvasHeight: self.imgViewBgHeight,
    })

    var picUrl = option.picUrl;
    if (picUrl && picUrl.length > 0) {
      this.setData({
        tempImageSrc: picUrl,
        originImageSrc: picUrl,
      })
      wx.showLoading({
        mask: true
      })
      loadImgOnImage(self)
    }

  },

  selectModel: function (op) {
    console.log(op)
    const index = op.currentTarget.dataset.index;
    if (index < this.data.modelList.length) {
      var minCutL = Math.max(0, this.data.imgLeft)
      var minCutT = Math.max(0, this.data.imgTop)
      this.setData({
        isCroper: true,
        selectModelIndex: index,
        cutL: minCutL,
        cutT: minCutT
      })
      var newW = this.data.imgWidth;
      var newH = this.data.imgHeight;
      this.setSacleModelChangeCut({
        newW: newW,
        newH: newH
      })
    }
  },

  loadImgOnImageSuccess: function () {
    this.openCroper()
  },

  onSureClick: function () {
    // 保存裁剪并进行返回
    this.setData({
      isSaveBack: true,
    })
    this.competeCrop()
  },

  onCancelClick: function () {
    wx.navigateBack({
      complete: (res) => { },
    })
  },

  resetClick: function () {
    var self = this;
    var originImageSrc = self.data.originImageSrc;

    self.setData({
      tempImageSrc: originImageSrc,
      isSaveBack: false,
      selectModelIndex: 0,
    }, () => {
      loadImgOnImage(self)

      self.device = wx.getSystemInfoSync()
      self.imgViewHeight = self.device.windowHeight - self.data.showBottomViewHeight
      self.imgViewWidth = self.device.windowWidth
      self.imgViewBgHeight = self.device.windowHeight - self.data.showBottomViewHeight;

      self.setData({
        imgViewHeight: self.imgViewHeight,
        imgViewWidth: self.imgViewWidth,
        tempCanvasHeight: self.imgViewHeight,
        tempCanvasWidth: self.imgViewWidth
      })
    })


  },

  sureCutClick: function () {
    this.setData({
      isSaveBack: false,
    })
    this.competeCrop();
  },

  uploadScaleStart(e) { //缩放图片

    console.log('uploadScaleStart');

    let self = this
    let xDistance, yDistance
    let [touch0, touch1] = e.touches
    //self.touchNum = 0 //初始化，用于控制旋转结束时，旋转动作只执行一次

    //计算第一个触摸点的位置，并参照该点进行缩放
    self.touchX = touch0.clientX
    self.touchY = touch0.clientY
    //每次触摸开始时图片左上角坐标
    self.imgLeft = self.startX
    self.imgTop = self.startY

    // 两指手势触发
    if (e.touches.length >= 2) {
      self.initLeft = (self.deviceRatio * self.data.criterionW / 2 - self.imgLeft) / self.oldScale
      self.initTop = (self.imgViewHeight / 2 - self.imgTop) / self.oldScale
      //计算两指距离
      xDistance = touch1.clientX - touch0.clientX
      yDistance = touch1.clientY - touch0.clientY
      self.oldDistance = Math.sqrt(xDistance * xDistance + yDistance * yDistance)
    }
  },

  uploadScaleMove(e) {
    // console.log('uploadScaleMove');
    fn(this, e)
  },

  uploadScaleEnd(e) {
    // console.log('uploadScaleEnd');
    let self = this
    self.oldScale = self.newScale || self.oldScale
    self.startX = self.imgLeft || self.startX
    self.startY = self.imgTop || self.startY
  },
  croperStart(e) {
    // console.log('croperStart');
    this.croperX = e.touches[0].clientX
    this.croperY = e.touches[0].clientY
  },
  croperMove(e) {
    // console.log('croperMove');
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;
    this.setLTModelXYChangeCut(clientX, clientY)

  },

  dragPointStart(e) {
    // console.log('dragPointStart');
    // console.log(e)
    var self = this
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;
    self.dragStartX = clientX;
    self.dragStartY = clientY;
    self.croperX = clientX;
    self.croperY = clientY;
    self.initDragCutW = self.data.cutW;
    self.initDragCutH = self.data.cutH;
  },

  dragPointMove(e) {
    // console.log('dragPointMove');
    const drag = e.currentTarget.dataset.drag;
    this.dragPointType = drag;
    if (drag == 'leftTop') {
      this.dragPinteLeftTop(e)
    } else if (drag == 'rightBottom') {
      this.dragPinteRightBottom(e)
    } else if (drag == 'bottomLeft') {
      this.dragPinteBottomLeft(e)
    } else if (drag == 'topRight') {
      this.dragPinteTopRight(e)
    } else {
      return;
    }
  },
  dragPinteLeftTop: function (e) {
    var self = this
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;

    // 我们要移动x、y、w、h、
    this.setModelChangeCut(clientX, clientY)
    this.setLTModelXYChangeCut(clientX, clientY)
  },

  dragPinteRightBottom: function (e) {
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;
    // 我们要移动w、h、
    this.setModelChangeCut(clientX, clientY)
  },

  dragPinteBottomLeft: function (e) {
    var self = this;
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;

    // 我们要移动x、w、h、
    this.setModelChangeCut(clientX, clientY)
    this.setLTModelXYChangeCut(clientX, self.croperY)
  },

  dragPinteTopRight: function (e) {
    var self = this;
    const clientX = e.touches[0].clientX;
    const clientY = e.touches[0].clientY;

    // 我们要移动x、w、h、
    this.setModelChangeCut(clientX, clientY)
    this.setLTModelXYChangeCut(self.croperX, clientY)
  },

  setLTModelXYChangeCut: function (clientX, clientY) {
    var self = this
    var dragLengthX = (clientX - self.croperX)
    var dragLengthY = (clientY - self.croperY)

    var newCutL = self.data.cutL + dragLengthX
    var newCutT = self.data.cutT + dragLengthY

    self.setLTModelChangeCut(newCutL, newCutT)

    self.croperX = clientX
    self.croperY = clientY
  },

  setLTModelChangeCut: function (newCutL, newCutT) {
    var self = this
    var minCutL = self.data.imgLeft
    var minCutT = self.data.imgTop

    var maxCutL = self.data.imgViewWidth - self.data.imgLeft - self.data.cutW
    var maxCutT = self.data.imgViewHeight - self.data.imgTop - self.data.cutH

    if (newCutL < minCutL) newCutL = minCutL
    if (newCutL > maxCutL) newCutL = maxCutL
    if (newCutT < minCutT) newCutT = minCutT
    if (newCutT > maxCutT) newCutT = maxCutT

    this.setData({
      cutL: newCutL,
      cutT: newCutT,
    })
  },

  setModelChangeCut: function (clientX, clientY) {
    var self = this

    var maxDragX = self.data.imgLeft + self.data.imgWidth
    var maxDragY = self.data.imgTop + self.data.imgHeight

    var dragMoveX = Math.min(clientX, maxDragX),
      dragMoveY = Math.min(clientY, maxDragY);

    var dragLengthX = dragMoveX - self.dragStartX
    var dragLengthY = dragMoveY - self.dragStartY

    var currentWX = 0
    var currentHY = 0

    const drag = self.dragPointType;
    if (drag == 'leftTop') {
      currentWX = self.initDragCutW - dragLengthX
      currentHY = self.initDragCutH - dragLengthY
    } else if (drag == 'rightBottom') {
      currentWX = dragLengthX + self.initDragCutW;
      currentHY = dragLengthY + self.initDragCutH;
    } else if (drag == 'bottomLeft') {
      currentWX = self.initDragCutW - dragLengthX;
      currentHY = dragLengthY + self.initDragCutH;
    } else if (drag == 'topRight') {
      currentWX = dragLengthX + self.initDragCutW;
      currentHY = self.initDragCutH - dragLengthY
    }

    // console.log('maxDragX', maxDragX )
    // console.log('maxDragY', maxDragY )
    // console.log('dragMoveX', dragMoveX )
    // console.log('dragMoveY', dragMoveY )
    // console.log('self.dragStartX',self.dragStartX)
    // console.log('self.dragStartY',self.dragStartY)
    // console.log('currentWX', currentWX )
    // console.log('currentHY', currentHY )
    // console.log('dragLengthX', dragLengthX )
    // console.log('dragLengthY', dragLengthY )
    // console.log('---------------------------')

    if (currentWX >= 0 && currentHY >= 0) {

      self.setSacleModelChangeCut({
        newW: currentWX,
        newH: currentHY
      })
    } else {
      return
    }
  },

  setSacleModelChangeCut: function (op) {
    var self = this;

    var newW = op.newW;
    var newH = op.newH;

    let imageW = self.data.imgWidth;
    let imageH = self.data.imgHeight;
    const model = self.data.modelList[self.data.selectModelIndex];
    var isController = false
    var scaleW = 0;
    var scaleH = 0;

    if (model) {
      if (model.sacleW > 0) {
        console.log('isController', isController)
        isController = true
        scaleW = model.sacleW;
        scaleH = model.sacleH;
      }
    }

    // console.log('scaleW', scaleW, "scaleH", scaleH)
    // console.log('newW', newW, "newH", newH)

    if (isController) {
      var scaleMaxH = 0;
      var scaleMaxW = 0;
      // console.log('imageW', imageW, 'imageH', imageH)
      if (imageW > imageH) {
        // 以imageH为计算
        scaleMaxH = imageH;
        var scale = imageH / scaleH;
        scaleMaxW = scaleW * scale;

        if (scaleMaxW > imageW) {
          const tempScale = imageW / scaleMaxW;
          scaleMaxH = scaleMaxH * tempScale;
          scaleMaxW = imageW;
        }

      } else {
        // 以imageW为计算
        scaleMaxW = imageW;
        var scale = imageW / scaleW;
        scaleMaxH = scaleH * scale;

        if (scaleMaxH > imageH) {
          const tempScale = imageH / scaleMaxH;
          scaleMaxW = scaleMaxW * tempScale;
          scaleMaxH = imageH;
        }
      }

      // console.log('scaleMaxH', scaleMaxH, 'scaleMaxW', scaleMaxW)

      // 2:3
      if (scaleMaxH > 0 && scaleMaxW > 0) {
        // 判断是否是宽高那个更大，
        if (newW > newH) {
          if (newW > scaleMaxW) {
            // 按照最大比例进行计算
            newW = scaleMaxW;
            newH = scaleMaxH;

          } else {
            // 按照正常比例进行计算            
            var scale = newH / scaleH;
            newW = scale * scaleW;

            if (newW > imageW) {
              const tempScale = imageW / newW;
              newH = newH * tempScale;
              newW = imageW;
            }

          }
        } else {
          if (newH > scaleMaxH) {
            // 按照最大比例进行计算
            newW = scaleMaxW;
            newH = scaleMaxH;
          } else {
            // 按照正常比例进行计算

            var scale = newW / scaleW;
            newH = scale * scaleH;

            if (newH > imageH) {
              const tempScale = imageH / newH;
              newW = newW * tempScale;
              newH = imageH;
            }
          }
        }
      }

      // console.log('newW', newW, 'newH', newH)
    }

    var maxDragX = self.data.imgLeft + self.data.imgWidth
    var maxDragY = self.data.imgTop + self.data.imgHeight
    const currentW = newW + self.data.imgLeft;
    const currentH = newH + self.data.imgTop;

    if (currentW > maxDragX) {
      newW = self.data.imgWidth;
    }

    if (currentH > maxDragY) {
      newH = self.data.imgHeight;
    }

    self.setData({
      cutW: newW,
      cutH: newH,
    })

  },

  onCancelClick() {
    wx.navigateBack({
      complete: (res) => { },
    })
  },

  openCroper() {
    console.log('openCroper');
    var minCutL = this.data.imgLeft
    var minCutT = this.data.imgTop
    const imageWidth = this.data.imgWidth;
    const imageHeight = this.data.imgHeight;
    this.setData({
      isCroper: true,
      cutW: imageWidth,
      cutH: imageHeight,
      cutL: minCutL,
      cutT: minCutT,
      selectModelIndex: 0
    })

    this.setSacleModelChangeCut({
      newW: imageWidth,
      newH: imageHeight
    })
  },

  competeCrop() {
    var self = this;
    wx.showLoading({
      title: '截取中',
      mask: true,
    });

    //图片截取大小
    var osX = (self.data.cutL - self.data.imgLeft);
    var osY = (self.data.cutT - self.data.imgTop);
    var osW = self.data.cutW;
    var osH = self.data.cutH;

    console.log(osX, osY, osW, osH);

    // self.initScaleWidth = self.scaleWidth;
    //   self.initScaleHeight = self.scaleHeight;
    //   self.orImageH = orImageH;
    //   self.orImageW = orImageW;
    const hS = self.orImageH / self.scaleHeight;
    const wS = self.orImageW / self.scaleWidth;

    var sX = osX * wS;
    var sY = osY * hS;
    var sW = osW * wS;
    var sH = osH * hS;

    // 变为图片原尺寸
    self.setData({
      isCroper: false,
      tempCanvasWidth: sW,
      tempCanvasHeight: sH
    });

    console.log(sX, sY, sW, sH);

    var ctx = wx.createCanvasContext('tempCanvas');
    ctx.drawImage(self.data.tempImageSrc, sX, sY, sW, sH, 0, 0, sW, sH);
    ctx.draw();

    //保存图片到临时路径
    saveImgUseTempCanvas(self, 100, loadImgOnImage);
  },

  cancelCrop() {
    this.setData({
      isCroper: false
    })
  },


  //保存照片
  saveImgToPhone() {
    wx.previewImage({
      urls: [this.data.tempImageSrc], // 需要预览的图片http链接列表        
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
// 公共方法

function loadImgOnImage(self) {
  wx.getImageInfo({
    src: self.data.tempImageSrc,
    success: function (res) {
      console.log('res', res)
      self.oldScale = 1

      const showMaxWidth = self.imgViewWidth - self.imageLeftAndRightGap;
      const showMaxHeight = self.imgViewHeight - self.imageLeftAndRightGap;

      // 图片原尺寸大小
      const orImageW = res.width;
      const orImageH = res.height;

      // 图片显示大小
      var showImageW = orImageW;
      var showimageH = orImageH;

      if (orImageH > showMaxHeight) {
        let sacele = showMaxHeight / orImageH;
        showimageH = showMaxHeight;
        showImageW = showImageW * sacele;
        if (showImageW > showMaxWidth) {
          let sacele1 = showMaxWidth / showImageW;
          showImageW = showMaxWidth
          showimageH = showimageH * sacele1;
        }
      } else if (orImageW > showMaxWidth) {
        let sacele = showMaxWidth / orImageW;
        showImageW = showMaxWidth
        showimageH = orImageH * sacele;
      }

      self.scaleWidth = showImageW;
      self.scaleHeight = showimageH;
      self.initScaleWidth = self.scaleWidth;
      self.initScaleHeight = self.scaleHeight;
      self.orImageH = orImageH;
      self.orImageW = orImageW;

      self.startX = self.imgViewWidth / 2 - self.scaleWidth / 2;
      self.startY = self.imgViewHeight / 2 - self.scaleHeight / 2;

      self.setData({
        imgWidth: self.scaleWidth,
        imgHeight: self.scaleHeight,
        imgTop: self.startY,
        imgLeft: self.startX
      })

      self.loadImgOnImageSuccess()
      wx.hideLoading();
    }
  })
}
function loadImgOnCanvas(self) {
  wx.getImageInfo({
    src: self.data.tempImageSrc,
    success: function (res) {

      // 图片原尺寸大小
      const orImageW = res.width;
      const orImageH = res.height;

      // 图片显示大小
      var showImageW = orImageW;
      var showimageH = orImageH;

      if (orImageH > showMaxHeight) {
        let sacele = showMaxHeight / orImageH;
        showimageH = showMaxHeight;
        showImageW = showImageW * sacele;
        if (showImageW > showMaxWidth) {
          let sacele1 = showMaxWidth / showImageW;
          showImageW = showMaxWidth
          showimageH = showimageH * sacele1;
        }
      } else if (orImageW > showMaxWidth) {
        let sacele = showMaxWidth / orImageW;
        showImageW = showMaxWidth
        showimageH = orImageH * sacele;
      }

      self.scaleWidth = showImageW;
      self.scaleHeight = showimageH;
      self.initScaleWidth = self.scaleWidth;
      self.initScaleHeight = self.scaleHeight;
      self.orImageH = orImageH;
      self.orImageW = orImageW;

      self.startX = self.imgViewWidth / 2 - self.scaleWidth / 2;
      self.startY = self.imgViewHeight / 2 - self.scaleHeight / 2;

      self.ctx = wx.createCanvasContext('myCanvas')
      self.ctx.translate(self.imgViewWidth / 2, self.imgViewHeight / 2) //原点移至中心，保证图片居中显示
      self.ctx.drawImage(self.data.tempImageSrc, self.startX, self.startY, self.scaleWidth, self.scaleHeight)
      self.ctx.draw()
    }
  })
}

function saveImgUseTempCanvas(self, delay, fn) {
  setTimeout(function () {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: self.data.tempCanvasWidth,
      height: self.data.tempCanvasHeight,
      destWidth: self.data.tempCanvasWidth,
      destHeight: self.data.tempCanvasHeight,
      fileType: 'png',
      quality: 1,
      canvasId: 'tempCanvas',
      success: function (res) {
        wx.hideLoading();
        console.log(res.tempFilePath)
        self.setData({
          tempImageSrc: res.tempFilePath
        })

        if (self.data.isSaveBack) {
          const eventChannel = self.data.events;
          if (eventChannel) {
            eventChannel.emit('onChangeUrl', { picUrl: res.tempFilePath });
          }

          wx.navigateBack({
            complete: (res) => { },
          })
        }

        if (fn) {
          fn(self)
        }
      }
    })
  }, delay)
}
